package com.jp.fm.servlet;

import java.io.IOException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jp.fm.data.BillReminder;

public class SaveReminders extends ServletParent {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public SaveReminders() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public final void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public final void doGet(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {

		doPost(request, response);
	}

	public final void doPost(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {

		final SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
		List<Integer> idsFromPage = new ArrayList<Integer>();

		// Build list of ids and names from the page
		Enumeration<String> paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {

			String name = paramNames.nextElement();

			if (name.startsWith("name_")) {

				String counter = name.substring(name.lastIndexOf('_') + 1);
				String brName = URLDecoder.decode(request.getParameter(name),
						"UTF-8");
				String id = request.getParameter("id_" + counter);

				if (null == id) {
					// insert a new record
					Float amount = Float.valueOf(request.getParameter("amount_"
							+ counter));

					String account = URLDecoder
							.decode(request.getParameter("account_" + counter),
									"UTF-8");

					Date dueDate = null;
					try {
						dueDate = sdf.parse(request.getParameter("datepicker_"
								+ counter));
					} catch (ParseException e) {
						e.printStackTrace();
					}
					String repeat = request.getParameter("repeat_" + counter);

					BillReminder br = new BillReminder(null, brName, amount,
							getAccountDao().findByName(account), dueDate,
							repeat);

					int newId = getBillReminderDao().writeObject(br);
					br.setId(newId);

					// Find the newly added BR and add its ID to the page list
					// so it does not get deleted below.
					idsFromPage.add(br.getId());
				}
			}

			if (name.startsWith("id_")) {
				idsFromPage.add(Integer.parseInt(request.getParameter(name)));
			}
		}

		doBillReminderDeletes(idsFromPage);

		RequestDispatcher rd = request.getRequestDispatcher("/");
		rd.forward(request, response);
	}

	protected void doBillReminderDeletes(final List<Integer> idsFromPage) {
		// do deletes by getting all reminders from the DB and iterating
		// over them.
		// If a reminder id does not exist in the request then remove it from
		// the DB.
		List<BillReminder> dbReminders = getBillReminderDao().findAll();
		for (Iterator<BillReminder> iterator = dbReminders.iterator(); iterator
				.hasNext();) {
			BillReminder billReminder = iterator.next();

			if (!idsFromPage.contains(billReminder.getId())) {
				// Delete it
				getBillReminderDao().delete(billReminder);
			}
		}
	}
}
